<template>
  <div class="pdf-viewer">
    <div class="controls">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
      <div class="scale-controls">
        <button @click="zoomOut">-</button>
        <span>{{ Math.round(currentScale * 100) }}%</span>
        <button @click="zoomIn">+</button>
        <button @click="fitToWidth">适合宽度</button>
        <button @click="fitToPage">适合页面</button>
      </div>
    </div>
    <div class="content-container">
      <!-- 左侧面板 -->
      <div class="left-panel" :style="{ width: leftPanelWidth + 'px' }">
        <div class="pdf-container">
          <div ref="viewerContainer" class="viewer-container">
            <div class="pdfViewer"></div>
          </div>
        </div>
      </div>
      
      <!-- 可拖拽的分割条 -->
      <div 
        class="resizer" 
        @mousedown="startResize"
        :class="{ 'resizing': isResizing }"
      ></div>
      
      <!-- 右侧面板 -->
      <div class="right-panel">
        <div class="placeholder">
          右侧内容区域
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as pdfjsLib from 'pdfjs-dist'
import * as pdfjsViewer from 'pdfjs-dist/web/pdf_viewer'
import 'pdfjs-dist/web/pdf_viewer.css'
import workerUrl from './pdf.worker.js?url'

pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl

const props = defineProps({
  pdfUrl: {
    type: String,
    required: true
  }
})

const viewerContainer = ref(null)
const currentPage = ref(1)
const totalPages = ref(0)
const leftPanelWidth = ref(800)
const isResizing = ref(false)
const currentScale = ref(1)
const autoFitWidth = ref(true) // 是否自动适应宽度
let pdfViewer = null
let pdfDocument = null
let resizeObserver = null

// 拖拽相关变量
let startX = 0
let startWidth = 0
let resizeTimeout = null

onMounted(async () => {
  try {
    await initPDFViewer()
    setupResizeObserver()
  } catch (error) {
    console.error('Error initializing PDF viewer:', error)
  }

  // 添加全局事件监听
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', stopResize)
})

onUnmounted(() => {
  // 清理事件监听
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', stopResize)
  
  // 清理ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect()
  }
  
  // 清理定时器
  if (resizeTimeout) {
    clearTimeout(resizeTimeout)
  }
})

// 初始化PDF viewer
const initPDFViewer = async () => {
  const container = viewerContainer.value
  
  // 创建eventBus
  const eventBus = new pdfjsViewer.EventBus()
  
  // 创建linkService
  const linkService = new pdfjsViewer.PDFLinkService({
    eventBus,
  })
  
  // 确保container中有pdfViewer元素
  const viewer = container.querySelector('.pdfViewer')
  
  // 创建viewer配置
  const viewerConfig = {
    container,
    viewer,
    eventBus,
    linkService,
    textLayerMode: 2,
    renderInteractiveForms: true,
  }
  
  // 初始化viewer
  pdfViewer = new pdfjsViewer.PDFViewer(viewerConfig)
  linkService.setViewer(pdfViewer)
  
  // 加载PDF文档
  const loadingTask = pdfjsLib.getDocument(props.pdfUrl)
  pdfDocument = await loadingTask.promise
  
  // 设置文档到viewer
  pdfViewer.setDocument(pdfDocument)
  linkService.setDocument(pdfDocument)
  
  totalPages.value = pdfDocument.numPages
  
  // 监听页面变化
  eventBus.on('pagechanging', (evt) => {
    currentPage.value = evt.pageNumber
  })

  // 监听缩放变化
  eventBus.on('scalechanging', (evt) => {
    currentScale.value = evt.scale
  })

  // 初始适应宽度
  await nextTick()
  setTimeout(() => {
    if (autoFitWidth.value) {
      fitToWidth()
    }
  }, 100)
}

// 监听leftPanelWidth变化
watch(leftPanelWidth, () => {
  if (autoFitWidth.value) {
    debouncedFitToWidth()
  }
})

// 设置ResizeObserver监听容器大小变化
const setupResizeObserver = () => {
  if ('ResizeObserver' in window && viewerContainer.value) {
    resizeObserver = new ResizeObserver(() => {
      if (autoFitWidth.value) {
        debouncedFitToWidth()
      }
    })
    resizeObserver.observe(viewerContainer.value)
  }
}

// 防抖的适应宽度函数
const debouncedFitToWidth = () => {
  if (resizeTimeout) {
    clearTimeout(resizeTimeout)
  }
  
  resizeTimeout = setTimeout(() => {
    fitToWidth()
  }, 150)
}

// 适应宽度
const fitToWidth = async () => {
  if (!pdfViewer || !pdfDocument) return
  
  try {
    await nextTick()
    
    const container = viewerContainer.value
    const containerWidth = container.clientWidth
    
    if (containerWidth <= 0) return
    
    // 获取第一页来计算原始尺寸
    const page = await pdfDocument.getPage(1)
    const viewport = page.getViewport({ scale: 1.0 })
    // 计算适合宽度的缩放比例，留出一些边距
    const padding = 40 // 左右各20px边距
    const scale = (containerWidth - padding) / (viewport.width * 1.3333)
    
    // 设置缩放比例
    pdfViewer.currentScale = Math.max(0.1, Math.min(scale, 3.0)) // 限制缩放范围
    autoFitWidth.value = true
    
  } catch (error) {
    console.warn('Error fitting to width:', error)
  }
}

// 适应页面（适合页面高度和宽度中的较小比例）
const fitToPage = async () => {
  if (!pdfViewer || !pdfDocument) return
  
  try {
    await nextTick()
    
    const container = viewerContainer.value
    const containerWidth = container.clientWidth
    const containerHeight = container.clientHeight
    
    if (containerWidth <= 0 || containerHeight <= 0) return
    
    // 获取第一页来计算原始尺寸
    const page = await pdfDocument.getPage(1)
    const viewport = page.getViewport({ scale: 1.0 })
    
    // 计算适合宽度和高度的缩放比例
    const padding = 40
    const scaleX = (containerWidth - padding) / viewport.width
    const scaleY = (containerHeight - padding) / viewport.height
    
    // 选择较小的缩放比例以确保整个页面都能显示
    const scale = Math.min(scaleX, scaleY)
    
    // 设置缩放比例
    pdfViewer.currentScale = Math.max(0.1, Math.min(scale, 3.0))
    autoFitWidth.value = false
    
  } catch (error) {
    console.warn('Error fitting to page:', error)
  }
}

// 放大
const zoomIn = () => {
  if (pdfViewer) {
    const newScale = currentScale.value * 1.25
    pdfViewer.currentScale = Math.min(newScale, 3.0)
    autoFitWidth.value = false
  }
}

// 缩小
const zoomOut = () => {
  if (pdfViewer) {
    const newScale = currentScale.value / 1.25
    pdfViewer.currentScale = Math.max(newScale, 0.1)
    autoFitWidth.value = false
  }
}

// 翻页方法
const prevPage = () => {
  if (pdfViewer && currentPage.value > 1) {
    pdfViewer.currentPageNumber = currentPage.value - 1
  }
}

const nextPage = () => {
  if (pdfViewer && currentPage.value < totalPages.value) {
    pdfViewer.currentPageNumber = currentPage.value + 1
  }
}

// 拖拽调整尺寸相关方法
const startResize = (e) => {
  isResizing.value = true
  startX = e.clientX
  startWidth = leftPanelWidth.value
  e.preventDefault()
}

const handleMouseMove = (e) => {
  if (!isResizing.value) return
  
  const deltaX = e.clientX - startX
  const newWidth = startWidth + deltaX
  
  // 设置最小和最大宽度限制
  const minWidth = 200
  const maxWidth = window.innerWidth - 200
  
  if (newWidth >= minWidth && newWidth <= maxWidth) {
    leftPanelWidth.value = newWidth
  }
}

const stopResize = () => {
  if (isResizing.value) {
    isResizing.value = false
  }
}
</script>

<style scoped>
.pdf-viewer {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.controls {
  display: flex;
  gap: 1rem;
  align-items: center;
  padding: 10px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
  flex-shrink: 0;
  flex-wrap: wrap;
}

.scale-controls {
  display: flex;
  gap: 0.5rem;
  align-items: center;
  margin-left: auto;
}

.scale-controls span {
  min-width: 50px;
  text-align: center;
}

.content-container {
  display: flex;
  flex: 1;
  overflow: hidden;
  min-height: 0;
}

.left-panel {
  display: flex;
  flex-direction: column;
  min-width: 200px;
  background: #fff;
  position: relative;
}

.pdf-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 0;
}

.viewer-container {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: auto;
  background: #f0f0f0;
}

.resizer {
  width: 4px;
  background: #e0e0e0;
  cursor: col-resize;
  position: relative;
  transition: background-color 0.2s;
  flex-shrink: 0;
}

.resizer:hover,
.resizer.resizing {
  background: #007acc;
}

.resizer::after {
  content: '';
  position: absolute;
  top: 0;
  left: -2px;
  right: -2px;
  bottom: 0;
}

.right-panel {
  flex: 1;
  background: #f9f9f9;
  border-left: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 0;
}

.placeholder {
  color: #666;
  font-size: 16px;
}

:deep(.pdfViewer) {
  margin: 0 auto;
}

:deep(.page) {
  margin: 9px auto -8px auto;
  border: 9px solid transparent;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

button {
  padding: 0.5rem 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
  background: white;
  font-size: 14px;
}

button:hover:not(:disabled) {
  background: #f0f0f0;
}

button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* PDF Viewer 样式 */
:deep(.textLayer) {
  position: absolute;
  text-align: initial;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  opacity: 1;
  line-height: 1.0;
  user-select: text;
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
}

:deep(.textLayer > span) {
  color: transparent;
  position: absolute;
  white-space: pre;
  cursor: text;
  transform-origin: 0% 0%;
}

:deep(.textLayer .highlight) {
  margin: -1px;
  padding: 1px;
  background-color: rgb(180, 0, 170);
  border-radius: 4px;
}

:deep(.textLayer ::selection) {
  background: rgb(0, 0, 255, 0.3);
}
</style>